// pages/component/authComponent/authComponent.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { register } from '../../../api/login';
import { Login } from '../../../store/user';

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  options: {
    addGlobalClass: true,
  },

  /**
   * 组件的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 获取授权手机号
    getPhoneNumber (e) {
      console.log(e.detail.code)
      var preUserId = wx.getStorageSync('preUserId');
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          // console.log(res,'res')
          if(res.code){
            wx.setStorageSync('loginCode', res.code)
            const params = preUserId == '' ? {loginCode: res.code, phoneCode: e.detail.code} : {loginCode: res.code, phoneCode: e.detail.code,preUserId: preUserId}
            register(params)
            .then(async(res1) => {
              if(res1.success){
                Login(res.code);
              }else{
                if(res1.errMessage == '当前手机号已注册' || res1.errMessage == '当前微信已注册'){
                  await Login(res.code);
                  this.triggerEvent('myevent')
                }else{
                  wx.showToast({
                    title: res1.errMessage,
                    icon: 'none',
                  })
                }
              }
            })
          }else{
            wx.showToast({
              title: '登录失败！' + res.errMsg,
              icon: 'none',
            })
          }
        }
      })
    },
  },
})
